package com.zmn.plat.admin.controller.servcategory;

import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto.VtDTO;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.plat.business.interfaces.product.productgroup.ProductGroupBService;
import com.zmn.plat.common.constant.ProductConsts;
import com.zmn.plat.common.dictionary.BaseAcceptProjectTypeEnum;
import com.zmn.plat.common.dictionary.ProductDict;
import com.zmn.plat.common.util.StringToArrayUtil;
import com.zmn.plat.model.entity.base.acceptproject.AcceptProject;
import com.zmn.plat.model.entity.base.acceptproject.AcceptProjectQuery;
import com.zmn.plat.model.entity.base.phenomenon.Phenomenon;
import com.zmn.plat.model.entity.base.phenomenon.PhenomenonQuery;
import com.zmn.plat.model.entity.base.servicecontent.ServiceContent;
import com.zmn.plat.model.entity.base.servicecontent.ServiceContentQuery;
import com.zmn.plat.model.entity.category.BaseCategory;
import com.zmn.plat.model.entity.product.productgroup.ProductGroup;
import com.zmn.plat.model.entity.product.productgroup.ProductGroupQuery;
import com.zmn.plat.model.entity.servcategory.*;
import com.zmn.plat.model.vo.servcategory.ServAssCategoryVO;
import com.zmn.plat.services.interfaces.product.productgroup.ProductGroupService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 服务分类、产品分类关联功能
 *
 * @author duanzuocai
 * @version v1.0
 * @since 2018/10/20 9:15
 */
@Controller
@RequestMapping("/serv/categ/ass/")
public class ServAssCategoryListController extends ServCategoryBaseController {
    private Logger logger = LoggerFactory.getLogger(ServAssCategoryListController.class);

    @Resource
    ProductGroupService productGroupService;

    @Resource
    ProductGroupBService productGroupBService;

    @RequiresPermissions("/serv/categ/ass/list.action")
    @RequestMapping(value = "list")
    public ModelAndView list(@ModelAttribute ServAssCategoryQuery query) {
        query.setShowType(ProductConsts.ERP_PRODUCT_TYPE);
        List<ServAssCategoryVO> items = servAssCategoryService.listPageByQuery(query);

        List<VtDTO> productGroupList = Collections.emptyList();
        if (NumberUtil.isPositiveInteger(query.getBizType())) {
            ProductGroupQuery groupQuery = new ProductGroupQuery();
            groupQuery.setBizType(query.getBizType());
            groupQuery.setStatus(GlobalConsts.YES);
            List<ProductGroup> productGroups = productGroupService.listByQuery(groupQuery);
            productGroupList = productGroups.stream().map(productGroup -> new VtDTO(productGroup.getGroupId(), productGroup.getName()))
                    .distinct().collect(Collectors.toList());
        }

        ModelAndView mav = new ModelAndView("servasscategory/list");

        List<VtDTO> categTwos = Collections.emptyList();
        List<BaseCategory> categOnes = baseCategoryService.listByParentId(GlobalConsts.TOP_ID, GlobalConsts.YES);
        List<ServCategory> servCategs = servCategoryService.listByQuery(new ServCategory());

        if (NumberUtil.isPositiveInteger(query.getCategOneId())) {
            categTwos = baseCategoryService.listByParentId(query.getCategOneId());
        }

        List<ShowCategoryAssociationVO> showCategoryAssociationList =
                showCategoryAssociationService.listByCategoryId(query.getServCategId(), query.getCategOneId(), query.getCategId());
        Map<String, List<ShowCategoryAssociationVO>> map = showCategoryAssociationList.stream()
                .collect(Collectors.groupingBy(e -> e.getServCategId() + "-" + e.getCategOneId() + "-" + e.getCategId()));
        items.forEach(e -> {
            List<ShowCategoryAssociationVO> data = map.get(e.getServCategId() + "-" + e.getCategOneId() + "-" + e.getCategId());
            if (!CollectionUtils.isEmpty(data)) {
                StringBuilder stringBuilder = new StringBuilder();
                data.forEach(mm -> stringBuilder.append(mm.getShowServCategName()).append("-").append(mm.getShowCategName()).append("、"));
                stringBuilder.deleteCharAt(stringBuilder.length() - 1);
                e.setRelateFrontCategStr(stringBuilder.toString());
            }
        });

        mav.addObject("servCategs", servCategs);
        mav.addObject("categOnes", categOnes);
        mav.addObject("categTwos", categTwos);
        mav.addObject("vo", query);
        mav.addObject("items", items);
        mav.addObject("bizTypeList", ProductDict.listBizType());
        mav.addObject("productGroupList", productGroupList);

        return mav;
    }

    /**
     * 信息
     */
    @RequestMapping("addEditView")
    @RequiresPermissions("/serv/categ/ass/addEditView.action")
    public ModelAndView addEditView(@RequestParam(value = "groupId", defaultValue = "0") Integer groupId) {
        ServAssCategory servAssCategory;
        if (groupId == 0) {
            servAssCategory = new ServAssCategory();
            servAssCategory.setGroupId(0);
        } else {
            servAssCategory = servAssCategoryService.findByKey(groupId);
        }

        List<VtDTO> bizTypeCList = productGroupBService.listVtByBizType(ProductConsts.BIZ_TYPE_C, GlobalConsts.YES);
        List<VtDTO> bizTypeFList = productGroupBService.listVtByBizType(ProductConsts.BIZ_TYPE_F, GlobalConsts.YES);
        List<VtDTO> bizTypeBList = productGroupBService.listVtByBizType(ProductConsts.BIZ_TYPE_B, GlobalConsts.YES);

        ModelAndView mav = new ModelAndView("servasscategory/detail");
        mav.addObject("servAssCategory", servAssCategory);
        mav.addObject("bizTypeCList", bizTypeCList);
        mav.addObject("bizTypeFList", bizTypeFList);
        mav.addObject("bizTypeBList", bizTypeBList);
        mav.addObject("flag", 2);
        return mav;
    }

    @RequestMapping("disclaimerView")
    public ModelAndView disclaimerView(@RequestParam(value = "groupId", defaultValue = "0") Integer groupId) {
        ServAssCategory servAssCategory = Optional.ofNullable(servAssCategoryService.findByKey(groupId)).orElse(new ServAssCategory());

        ModelAndView mav = new ModelAndView("servasscategory/disclaimer");
        mav.addObject("servAssCategory", servAssCategory);
        mav.addObject("flag", 1);
        return mav;
    }


    @RequestMapping("faultView")
    public ModelAndView faultView(@RequestParam(value = "groupId", defaultValue = "0") Integer groupId) {
        ServAssCategory servAssCategory = Optional.ofNullable(servAssCategoryService.findByKey(groupId)).orElse(new ServAssCategory());
        // 已关联的故障信息
        List<VtDTO> listFault = new ArrayList<>();
        if (StringUtil.isNotBlank(servAssCategory.getFault())) {
            final List<Integer> listFaultIds = StringToArrayUtil.convertStrsToList(servAssCategory.getFault());
            final List<Phenomenon> phenomena = phenomenonService.listByIds(listFaultIds);
            listFault = phenomena.stream().map(x -> new VtDTO(x.getPhenId(), x.getPhenName()+"-"+x.getPhenId())).collect(Collectors.toList());
        }
        String listFaultName = Optional.ofNullable(listFault.stream().map(VtDTO::getText).collect(Collectors.joining(","))).orElse("");
        ModelAndView mav = new ModelAndView("servasscategory/fault");
        mav.addObject("servAssCategory", servAssCategory);
        mav.addObject("listFault", listFault);
        mav.addObject("listFaultName", listFaultName);
        mav.addObject("flag", 3);
        return mav;
    }

    @ResponseBody
    @RequestMapping("selectListfault")
    public ResponseDTO<Map<String, Object>> selectListfault(@ModelAttribute SelectQuery query) {
        // 获取关联后的
        PhenomenonQuery phenomenonQuery = BeanMapper.map(query, PhenomenonQuery.class);
        phenomenonQuery.setIdOrPhenName(query.getKeyWord());
        phenomenonQuery.setStatus(GlobalConsts.YES);

        List<Phenomenon> faultPhenomena = Optional.ofNullable(phenomenonService.listByQuery(phenomenonQuery))
                .orElse(Collections.emptyList());

        List<VtDTO> list = faultPhenomena.stream()
                .map(x -> new VtDTO(x.getPhenId(), x.getPhenName()+"-"+x.getPhenId(), x.getStatus()))
                .collect(Collectors.toList());

        Map<String, Object> result = new HashMap<>(4);
        result.put("totalCount", phenomenonQuery.getTotalCount());
        result.put("list", list);
        return ResponseDTO.success(result);
    }

    @RequestMapping("acceptProjectView")
    public ModelAndView acceptProjectView(@RequestParam(value = "groupId", defaultValue = "0") Integer groupId) {
        ServAssCategory servAssCategory = Optional.ofNullable(servAssCategoryService.findByKey(groupId)).orElse(new ServAssCategory());
        // 已关联的故障信息
        List<VtDTO> listEngineerAcceptProject;
        List<VtDTO> listUserAcceptProject;

        List<Integer> acceIds = new ArrayList<>();
        if (StringUtil.isNotBlank(servAssCategory.getEngineerAcceptProject())) {
            acceIds.addAll(StringToArrayUtil.convertStrsToList(servAssCategory.getEngineerAcceptProject()));
        }
        if (StringUtil.isNotBlank(servAssCategory.getUserAcceptProject())) {
            acceIds.addAll(StringToArrayUtil.convertStrsToList(servAssCategory.getUserAcceptProject()));
        }

        final List<AcceptProject> listAccept = baseAcceptProjectService.listByIds(acceIds);
        listEngineerAcceptProject = getVtDTOS(listAccept, BaseAcceptProjectTypeEnum.ENGINEER_ACCEPT.getCode());
        String engineerAcceptProject = Optional.ofNullable(
                        listEngineerAcceptProject.stream()
                                .map(VtDTO::getText)
                                .collect(Collectors.joining(",")))
                .orElse("");

        listUserAcceptProject = getVtDTOS(listAccept, BaseAcceptProjectTypeEnum.USER_ACCEPT.getCode());
        String userAcceptProject = Optional.ofNullable(
                        listUserAcceptProject.stream()
                                .map(VtDTO::getText)
                                .collect(Collectors.joining(",")))
                .orElse("");

        ModelAndView mav = new ModelAndView("servasscategory/accep_project");
        mav.addObject("servAssCategory", servAssCategory);
        mav.addObject("listEngineerAcceptProject", listEngineerAcceptProject);
        mav.addObject("engineerAcceptProject", engineerAcceptProject);
        mav.addObject("listUserAcceptProject", listUserAcceptProject);
        mav.addObject("userAcceptProject", userAcceptProject);
        mav.addObject("flag", 4);
        return mav;
    }

    @ResponseBody
    @RequestMapping("selectListAcceptProject")
    public ResponseDTO<Map<String, Object>> selectListAcceptProject(@ModelAttribute SelectQuery query) {
        // 获取关联后的
        final Integer type = NumberUtil.isNullOrZero(query.getType()) ? BaseAcceptProjectTypeEnum.ENGINEER_ACCEPT.getCode() : query.getType();
        AcceptProjectQuery phenomenonQuery = BeanMapper.map(query, AcceptProjectQuery.class);
        phenomenonQuery.setAcceIdOrName(query.getKeyWord());
        phenomenonQuery.setAcceType(type);
        phenomenonQuery.setStatus(GlobalConsts.YES);
        List<AcceptProject> faultPhenomena = baseAcceptProjectService.listByQuery(phenomenonQuery);
        List<VtDTO> list = getVtDTOS(faultPhenomena, type);
        Map<String, Object> result = new HashMap<>(4);
        result.put("totalCount", phenomenonQuery.getTotalCount());
        result.put("list", list);
        return ResponseDTO.success(result);
    }


    @ResponseBody
    @RequestMapping("selectListUserAcceptProject")
    public ResponseDTO<Map<String, Object>> selectListUserAcceptProject(@ModelAttribute SelectQuery query) {
        query.setType(BaseAcceptProjectTypeEnum.USER_ACCEPT.getCode());
        return selectListAcceptProject(query);
    }

    @RequestMapping("serviceContentView")
    public ModelAndView serviceItemView(@RequestParam(value = "groupId", defaultValue = "0") Integer groupId) {
        ServAssCategory servAssCategory = Optional.ofNullable(servAssCategoryService.findByKey(groupId)).orElse(new ServAssCategory());
        // 已关联的故障信息
        List<VtDTO> listServiceContent = new ArrayList<>();
        if (StringUtil.isNotBlank(servAssCategory.getServiceContent())) {
            final List<Integer> serviceContent = StringToArrayUtil.convertStrsToList(servAssCategory.getServiceContent());
            listServiceContent = Optional.ofNullable(baseServiceItemService.listByIds(serviceContent)
                    .stream()
                    .map(x -> new VtDTO(x.getServId(), x.getServDesc()+"-"+x.getServId()))
                    .collect(Collectors.toList())).orElse(new ArrayList<>());
        }
        String serviceContent = Optional.ofNullable(
                        listServiceContent.stream()
                                .map(VtDTO::getText)
                                .collect(Collectors.joining(",")))
                .orElse("");

        ModelAndView mav = new ModelAndView("servasscategory/service_content");
        mav.addObject("servAssCategory", servAssCategory);
        mav.addObject("listServiceContent", listServiceContent);
        mav.addObject("serviceContentName", serviceContent);
        mav.addObject("flag", 5);
        return mav;
    }

    @ResponseBody
    @RequestMapping("selectListServiceContent")
    public ResponseDTO<Map<String, Object>> serviceItem(@ModelAttribute SelectQuery query) {
        // 获取关联后的
        ServiceContentQuery phenomenonQuery = BeanMapper.map(query, ServiceContentQuery.class);
        phenomenonQuery.setServIdOrDesc(query.getKeyWord());
        phenomenonQuery.setStatus(GlobalConsts.YES);
        List<ServiceContent> faultPhenomena = Optional.ofNullable(baseServiceItemService.listByQuery(phenomenonQuery))
                .orElse(Collections.emptyList());
        List<VtDTO> list = faultPhenomena.stream()
                .map(x -> new VtDTO(x.getServId(), x.getServDesc()+"-"+x.getServId(), x.getStatus()))
                .collect(Collectors.toList());
        Map<String, Object> result = new HashMap<>(4);
        result.put("totalCount", phenomenonQuery.getTotalCount());
        result.put("list", list);
        return ResponseDTO.success(result);
    }

    @RequestMapping("tstDripView")
    public ModelAndView tstDripView(@RequestParam(value = "groupId", defaultValue = "0") Integer groupId) {
        ServAssCategory servAssCategory = Optional.ofNullable(servAssCategoryService.findByKey(groupId)).orElse(new ServAssCategory());
        // 已关联的故障信息
        List<VtDTO> listServiceItem = new ArrayList<>();
        ModelAndView mav = new ModelAndView("servasscategory/tst_drip");
        mav.addObject("servAssCategory", servAssCategory);
        mav.addObject("flag", 7);
        return mav;
    }

    @NotNull
    private List<VtDTO> getVtDTOS(List<AcceptProject> listAccept, Integer acceType) {
        List<VtDTO> listEngineerAcceptProject = new ArrayList<>();
        if (CollectionUtil.isNullOrEmpty(listAccept)) {
            return listEngineerAcceptProject;
        }
        listEngineerAcceptProject = Optional.ofNullable(
                        listAccept.stream()
                                .filter(x -> Objects.equals(x.getAcceType(), acceType))
                                .map(x -> new VtDTO(x.getAcceId(), x.getAcceName()+"-"+x.getAcceId()))
                                .collect(Collectors.toList()))
                .orElse(new ArrayList<>());
        return listEngineerAcceptProject;
    }
}
